import {Component} from "@angular/core";
import {IonicPage, LoadingController, NavController, NavParams, Platform, ToastController} from "ionic-angular";
import {DomSanitizer} from "@angular/platform-browser";
import $ from "jquery";

import {InformationDetailProvider} from '../../../providers/information/information-detail/information-detail.provider';
import {InfoDetail} from '../../../model/pages/information/information-detail/information-detail.model';
import {ToastService} from '../../../services/common/toast.service';
import {LoadingService} from "../../../services/common/loading.service";
import {FileService} from "../../../services/native/file/file.service";
import {FileOpener} from "@ionic-native/file-opener";
import {FileTransfer} from "@ionic-native/file-transfer";
import {LocalStorageService} from "../../../services/native/local-storage/local-storage.service";
import {WechatService} from "../../../services/native/wechat/wechat.service";
import {BASEURL} from "../../../config/url.config";
import {ThemeBrowserService} from '../../../services/native/theme-browser/theme-browser.service';
import {PermissionsService} from "../../../services/native/permissions/permissions.service";
import {Utils} from "../../../services/utils/utils.services";

@IonicPage()
@Component({
    selector: 'page-information-detail',
    templateUrl: 'information-detail.html',
    providers: [
        InformationDetailProvider,
        ToastService,
        FileService,
        FileOpener,
        FileTransfer,
        LocalStorageService,
        WechatService,
        Utils,
        ThemeBrowserService,
        PermissionsService
    ]
})
export class InformationDetailPage {
    // 当前信息id
    private contentId:any;
    // 当前信息收藏状态
    private collectStatus:boolean;
    // 资讯详情
    private infoDetail:InfoDetail=new InfoDetail();
    // 是否显示收藏按钮
    private collectBtnStatus:boolean;
    // 外链接
    private outLinkUrl:any;
    // 请求状态
    private requestStatus:boolean;
    // 是否已经分享
    showShareMenu: boolean;
    //附件
    attachFiles: any;
    // 收藏请求
    collectResquest:boolean=true;
    // azuro
    azureInfo:any;

    constructor(private navParams: NavParams,
                private navCtrl: NavController,
                private informationDetailProvider: InformationDetailProvider,
                private toastCtrl:ToastController,
                private sanitizer: DomSanitizer,
                private toastService:ToastService,
                private load: LoadingService,
                private fileService: FileService,
                private fileOpener: FileOpener,
                private loadingCtrl: LoadingController,
                public wechatService: WechatService,
                private platform: Platform,
                private permissionsService: PermissionsService,
                public themeBrowserService:ThemeBrowserService,
                public utils:Utils
                ) {
    }

    public backButtonHandle = () => this.backClickHandle();

    ionViewDidLoad() {
        this.contentId= this.navParams.get('id');
        this.navParams.get('status')?this.collectBtnStatus=false:this.collectBtnStatus=true;
        this.outLinkUrl=this.navParams.get('url')?this.sanitizer.bypassSecurityTrustResourceUrl(this.navParams.get('url')):null;
        this.getInfoDetail(this.contentId);
    }

    // 返回
    backClickHandle(){
        this.navCtrl.pop();
    }

    // 获取详情
    getInfoDetail(id) {
        this.load.showLoading();
        this.informationDetailProvider.getInfoDetail(id).subscribe((res) => {
            if(res.id){
                this.infoDetail=res;
                this.infoDetail.status?this.collectStatus=true:this.collectStatus=false;
                this.getAzureInfo ();
            }
            this.requestStatus=true;
            this.attachFiles = res.attachFiles;
            this.load.dismissLoading();
        },err=>{
            this.requestStatus=true;
            this.load.dismissLoading();
        })
    }

    // 获取azuro图片信息
    getAzureInfo () {
        this.fileService.getAzureInfo().subscribe((data) => {
            this.azureInfo = data.azureInfo;
            this.infoDetail.imgUrl=this.fileService.getCompletePath(this.infoDetail.imgUrl, this.azureInfo);
        }, err => {
            this.azureInfo='error'
        });
    }

    // a标签重新渲染完成
    renderEnd(flag){
        if(flag)this.signLink($);
    }

    // 收藏咨询
    setInfoCollect() {
        if(!this.collectResquest){
            return false;
        }else{
            this.collectResquest=false;
        }
        if(this.collectStatus){
            this.cancelCollect(this.infoDetail['id']);
            return false;
        }
        this.collectInfo(this.infoDetail['id']);
    }

    // 收藏资讯
    collectInfo(id){
        this.informationDetailProvider.collectInfo(id).subscribe((res)=>{
            this.collectStatus=true;
            this.collectResquest=true;
        },error=>{
            this.collectResquest=true;
        });
    }

    // 取消收藏
    cancelCollect(id){
        this.informationDetailProvider.cancelCollect(id).subscribe((res)=>{
            this.collectStatus=false;
            this.collectResquest=true;
        },error=>{
            this.collectResquest=true;
        });
    }

    // a标签链接
    signLink($){
        let $this=this;
        $(".info-bd a").on("click",function(e){
            e.stopPropagation();
            e.preventDefault();
            let link=$(this).attr('link');
            if(link){
                $this.themeBrowserService.openBrowser(link);
            }
            return false;
        })
    }

    openAttachFile(resourceId: string, realFileName: string) {
        if(this.platform.is('android')) {
            this.permissionsService.checkAndroidStoragePermission().then(res => {
                if (res == 'GRANTED') {
                    this.viewAttachFile(resourceId,realFileName);
                } else if (res == 'DENIED') {
                    this.toastService.showToast('请到“设置>应用”中启用“存储”权限');
                    return;
                }
            }).catch(e => {
                console.log('检查存储权限异常',e);
            })
        } else {
            this.viewAttachFile(resourceId,realFileName);
        }
    }

    /**
     * 打开附件
     * @param {string} resourceId
     */
    viewAttachFile(resourceId: string, realFileName: string) {

        let now = 0;
        console.log(resourceId);
        let loading = this.loadingCtrl.create({
            spinner: 'circles',
            content: '文件加载中: 0%',
            dismissOnPageChange: false,
            enableBackdropDismiss: true
        });
        if (resourceId) {
            loading.onDidDismiss(() => {
                // console.log('on did dissmisse');
                this.fileService.abort();
            });
            loading.present();

            this.fileService.onProgress(progressEvent => {
                if (progressEvent.lengthComputable) {
                    // console.log(progressEvent.loaded +'/' + progressEvent.total);
                    now = progressEvent.loaded / progressEvent.total * 100;
                }
            });

            let mTimer = setInterval(() => {
                loading.setContent('文件加载中: ' + Math.floor(now) + '%');
                if (now >= 99) {
                    clearInterval(mTimer);
                }
            }, 300);

            this.fileService.getFile(resourceId,realFileName).subscribe(res => {
                    // console.log('get ssssssssss');
                    console.log(res);

                    loading.dismiss();
                    // now = 0;

                    setTimeout(()=> {
                        let fileUrl = res.fileUrl;
                        let mimeType = res.mimeType;
                        console.log('fileUrl' + fileUrl);
                        console.log('fileUrl' + decodeURI(fileUrl));
                        console.log('mineType' + mimeType);
                        this.fileOpener.open(decodeURI(fileUrl), mimeType)
                            .then(() => {
                                console.log('file is open success,fileUrl is : '
                                    + fileUrl + 'mimeType is: ' + mimeType);
                            })
                            .catch(e => {
                                console.log('file is open failed,fileUrl is : '
                                    + fileUrl + 'mimeType is: ' + mimeType, e);
                                if (e.message.indexOf('No Activity found to handle Intent') > -1) {
                                    if (e.message.indexOf('application/pdf') > -1) {
                                        this.toastService.showToast('请至应用商店下载安装PDF阅读器');
                                    } else if (e.message.indexOf('video/mp4') > -1) {
                                        this.toastService.showToast('请至应用商店下载安装MP4播放器');
                                    }
                                }

                                this.toastService.showToast('文件打开失败');
                            });
                    },300);
                },
                error2 => {
                    console.log('get file error', error2);
                    loading.dismiss();
                    // now = 0;
                    if (error2.code == 4 && error2.http_status == -1) {
                        this.toastService.showToast('取消加载');
                    } else {
                        this.toastService.showToast('文件加载失败，请稍后重试');
                    }

                });
        } else {
            loading.dismiss();
            this.toastService.showToast('文件异常');
        }

    }

    /**
     * 补全URL路径
     */
    completionUrl(id) {
        return id ? BASEURL + '/azure/v1/download?resourceId=' + id :
            './assets/images/activity/activity-details/none-data.jpg';
    }


    /**
     * 分享资讯
     */
    shareInfo(scene) {
        let roles = localStorage.getItem('roles');
        let des = this.utils.DelHtmlTag(this.infoDetail.infoDetail.replace(/(&nbsp;)|(&nbsp)|(&nbs)|(&nb)|(&n)/g, ''));
        //let des = this.utils.DelHtmlTag(this.infoDetail.infoDetail);
        //分享给朋友0,分享到朋友圈1
        this.wechatService.share(scene, 'send-link-thumb-remote',
            {
                // link: 'http://localhost:63342/ADP_Minisite/index.html'+'?id='
                // +this.infoDetail.id+'&agentCode='+localStorage.getItem('userName'),
                link: this.infoDetail.shareUrl,
                thumb: this.navParams.get('imgUrl')?this.navParams.get('imgUrl'):this.infoDetail.imgUrl,
                shortName:this.infoDetail.title,
                description: des

            }, () => {
                loading.dismiss();
            }
            ,reason => {
                if(reason!='用户点击取消并返回'){
                    this.toastService.showToast(`分享失败:${reason}`);
                }
                loading.dismiss();
            }
        );
        this.informationDetailProvider.shareInfoRoles(this.infoDetail.id,roles).subscribe(res=>{
            console.log("分享资讯成功");
        });
        let loading = this.loadingCtrl.create({
            spinner: 'circles',
            content: '正在打开微信',
            dismissOnPageChange: false,
            enableBackdropDismiss: true
        });
        loading.present();
        setTimeout(() => {
            loading.dismiss();
        },10000);
    }
}
